package com.bhs.sansong.ui.wallet;

import android.annotation.SuppressLint;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bhs.sansong.R;
import com.bhs.sansong.adapter.StickyExampleAdapter;
import com.bhs.sansong.base.BaseActivity;
import com.bhs.sansong.bean.BillBean;
import com.bhs.sansong.bean.BillDataBean;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.utils.DateUtils;
import com.bhs.sansong.utils.ToastUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 红包记录
 */
public class RedEnvelopeRecordActivity extends BaseActivity implements NetCallBack {

    private TextView mTvDate;

    private RecyclerView mRvList;
    private int page = 1;
    private StickyExampleAdapter mAdapter;
    private SwipeRefreshLayout refreshLayout;
    private List<BillBean> mList = new ArrayList<>();
    private boolean isLoadingNextPage;
    private boolean loadingCompleted;

    @Override
    public int initLayout() {
        return R.layout.activity_red_envelope_record;
    }

    @Override
    public void initView() {
        TextView mTvTitle = findViewById(R.id.tv_title);
        mTvTitle.setText("红包记录");
        mRvList = findViewById(R.id.rv_list);
        mAdapter = new StickyExampleAdapter(mActivity, mList);
        refreshLayout = findViewById(R.id.refreshLayout);
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(mActivity));
        mTvDate = findViewById(R.id.tv_date);
    }

    @Override
    public void initData() {
        loadData();
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                loadData();
            }
        });


        mRvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager Im = (LinearLayoutManager) recyclerView.getLayoutManager();
                int lastVisibleItemPosition = Im.findLastVisibleItemPosition();
                int totalCount = Im.getItemCount();
                if (lastVisibleItemPosition == totalCount - 1 && !refreshLayout.isRefreshing() && !isLoadingNextPage && !loadingCompleted) {
                    if (totalCount > 0) {
                        // 在 recyclerView 滚动时向列表中添加item 并调用 notifyItemInserted() 方法更新时，
                        // 系统会给出 warning: 可能会影响RecyclerView滑动时的高度等测量
                        // 所以将这次更新 UI 的操作，延迟到下一帧绘制。
                        recyclerView.post(() -> {
                            isLoadingNextPage = true;
                            page++;
                            loadData();
                        });
                    }
                }
            }
        });
        sticky();
    }

    private void sticky() {
        mRvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                View stickyInfoView = recyclerView.findChildViewUnder(
                        mTvDate.getMeasuredWidth() / 2, 5);

                if (stickyInfoView != null && stickyInfoView.getContentDescription() != null) {
                    mTvDate.setText(String.valueOf(stickyInfoView.getContentDescription()));
                }

                View transInfoView = recyclerView.findChildViewUnder(
                        mTvDate.getMeasuredWidth() / 2, mTvDate.getMeasuredHeight() + 1);

                if (transInfoView != null && transInfoView.getTag() != null) {

                    int transViewStatus = (int) transInfoView.getTag();
                    int dealtY = transInfoView.getTop() - mTvDate.getMeasuredHeight();

                    if (transViewStatus == StickyExampleAdapter.HAS_STICKY_VIEW) {
                        if (transInfoView.getTop() > 0) {
                            mTvDate.setTranslationY(dealtY);
                        } else {
                            mTvDate.setTranslationY(0);
                        }
                    } else if (transViewStatus == StickyExampleAdapter.NONE_STICKY_VIEW) {
                        mTvDate.setTranslationY(0);
                    }
                }
            }
        });
    }

    private void loadData() {
        Map<String, String> map = new ArrayMap<>();
        map.put("page", String.valueOf(page));
        map.put("limit", "11");
        map.put("wallet_type", "money02");
        networkRequest(netApi.get_wallet_log(map), this);
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        BillDataBean bean = new Gson().fromJson(json, BillDataBean.class);
        refreshLayout.setRefreshing(false);
        isLoadingNextPage = false;
        if (bean.isStatus()) {
            if (page == 1) {
                mList.clear();
                loadingCompleted = false;
                for (BillBean billBean : bean.getData().getList()) {
                    if (billBean.getLog_id() > 0) {
                        mList.add(billBean);
                    }
                }
                mAdapter.notifyDataSetChanged();
            } else {
                for (BillBean billBean : bean.getData().getList()) {
                    if (billBean.getLog_id() > 0) {
                        mList.add(billBean);
                    }
                }
                mAdapter.notifyDataSetChanged();
            }

            if (mList.size() >= bean.getData().getTotal_count()) {
                loadingCompleted = true;
            }
        } else {
            ToastUtil.show(bean.getMsg());
        }
    }

    @Override
    public void onFailure(int requestCode) {
        refreshLayout.setRefreshing(false);
        isLoadingNextPage = false;
    }
}